package com.llg.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.llg.mapper.ProcessorBrandMapper;
import com.llg.model.code.CommonCode;
import com.llg.model.code.PageCode;
import com.llg.model.response.DataResult;
import com.llg.model.response.PageResult;
import com.llg.model.response.ResponseResult;
import com.llg.pojo.ProcessorBrand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class ProcessorBrandService {
    @Autowired
    private ProcessorBrandMapper mapper;

    //查所有
    public PageResult<ProcessorBrand> findAll(){
        List<ProcessorBrand> list = mapper.selectAll();
        return new PageResult<>(CommonCode.SUCCESS, list.size(), 1, list);
    }

    //分页搜索查
    public PageResult<ProcessorBrand> findList(int currentPage,int pageSize,ProcessorBrand processorBrand){
        //判断参数是否合法
        if(currentPage <= 0) return new PageResult<>(PageCode.PAGE_ERR1, 0, 0, null);
        if(pageSize <= 0) return new PageResult<>(PageCode.SIZE_ERR, 0, 0, null);
        PageHelper.startPage(currentPage, pageSize);
        Example example = new Example(ProcessorBrand.class);
        Example.Criteria criteria = example.createCriteria();
        if (processorBrand != null) {
            if (processorBrand.getName() != null && !processorBrand.getName().equals("")) {
                criteria.andLike("name", "%"+processorBrand.getName()+"%");
            }
        }
        List<ProcessorBrand> list = mapper.selectByExample(example);
        PageInfo<ProcessorBrand> page = new PageInfo<>(list);
        return new PageResult<>(CommonCode.SUCCESS, (int) page.getTotal(), page.getPages(), page.getList());

    }

    //通过id查
    public DataResult<ProcessorBrand> findById(int id){
        return new DataResult<>(CommonCode.SUCCESS, mapper.selectByPrimaryKey(id));
    }

    //增
    public DataResult<ProcessorBrand> add(ProcessorBrand processorBrand){
        mapper.insertSelective(processorBrand);
        return new DataResult<>(CommonCode.SUCCESS, processorBrand);
    }

    //删
    public ResponseResult delete(int id){
        mapper.deleteByPrimaryKey(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //改
    public ResponseResult update(ProcessorBrand processorBrand){
        mapper.updateByPrimaryKeySelective(processorBrand);
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
